package com.coderush.admin.core.exception;

import com.coderush.admin.core.response.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.DispatcherServlet;

import java.sql.SQLException;

@Slf4j
@RestControllerAdvice
@ConditionalOnClass({DispatcherServlet.class})
public class GlobalExceptionHandler {


    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<Void> handleBusinessException(BusinessException e) {
        log.error("业务异常：{}", e.getMessage(), e);
        return Result.buildFail(e.getCode(), e.getMessage());
    }

    /**
     *
     * 空指针异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    public Result<String> handlerNullPointerException(HttpServletRequest req, HttpServletResponse res, NullPointerException e) {

        log.error("捕获全局异常,NullPointerException: url : {} , exception : {}", req.getRequestURI(), e.getMessage());

        return Result.buildFail(500, "系统异常");
    }

    /**
     * 处理参数验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("参数验证异常：{}", e.getMessage());
        e.printStackTrace();
        StringBuilder errorMsg = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(error ->
                errorMsg.append(error.getField()).append(": ").append(error.getDefaultMessage()).append("; ")
        );

        return Result.buildFail(400, "参数验证失败: " + errorMsg.toString());
    }

    /**
     * 处理请求参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    public Result<String> handleBindException(BindException e) {
        log.error("参数绑定异常：{}", e.getMessage(), e);

        StringBuilder errorMsg = new StringBuilder();
        e.getBindingResult().getFieldErrors().forEach(error ->
                errorMsg.append(error.getField()).append(": ").append(error.getDefaultMessage()).append("; ")
        );

        return Result.buildFail(400, "参数绑定失败: " + errorMsg.toString());
    }

    /**
     * 处理请求参数类型转换异常
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public Result<String> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        log.error("参数类型转换异常：{}", e.getMessage(), e);
        return Result.buildFail(400, "参数类型错误: " + e.getName() + " 应为 " + e.getRequiredType().getSimpleName());
    }

    /**
     * 处理HTTP请求方法不支持异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<String> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.error("HTTP请求方法不支持：{}", e.getMessage(), e);
        return Result.buildFail(405, "请求方法不支持: " + e.getMethod());
    }

    /**
     * 处理HTTP媒体类型不支持异常
     */
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public Result<String> handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
        log.error("HTTP媒体类型不支持：{}", e.getMessage(), e);
        return Result.buildFail(415, "媒体类型不支持: " + e.getContentType());
    }

    /**
     * 处理数组越界异常
     */
    @ExceptionHandler(IndexOutOfBoundsException.class)
    public Result<String> handleIndexOutOfBoundsException(IndexOutOfBoundsException e) {
        log.error("数组越界异常：{}", e.getMessage(), e);
        return Result.buildFail(500, "服务器内部错误，请联系管理员");
    }

    /**
     * 处理SQL异常
     */
    @ExceptionHandler(SQLException.class)
    public Result<String> handleSQLException(SQLException e) {
        log.error("数据库异常：{}", e.getMessage(), e);
        return Result.buildFail(500, "数据库操作异常，请联系管理员");
    }

    /**
     *
     * @param req
     * @param res
     * @param e
     * @return
     */
    @ExceptionHandler(ValidationException.class)
    public Result<String> handlerParamValidException(HttpServletRequest req, HttpServletResponse res, Exception e) {

        log.error("请求参数错误: url : {} , exception : {}", req.getRequestURI(), e.getMessage());

        return Result.buildFail(400, "请求参数错误");
    }


    /**
     * 全局的异常处理
     * @param req
     * @param res
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result<String> handlerException(HttpServletRequest req, HttpServletResponse res, Exception e) {

        e.printStackTrace();

        res.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());

        log.error("全局异常: url : {} , exception : {}", req.getRequestURI(), e.getMessage());

        return Result.buildFail(500, "服务器内部错误，请联系管理员");
    }

}